﻿
    layui.use(['table', 'form', 'jquery', 'layer'], function () {
        var table = layui.table;
    var form = layui.form;
    var laydate = layui.laydate;
    var layer = layui.layer;
    var $ = layui.$;

    // 渲染
    laydate.render({
        elem: '#ID-laydate-demo'
    });

    $('#addRowBtn').on('click', function () {
        // 获取数据表格和行数
        const table = document.getElementById('dataTable');
        const numRows = table.rows.length;

        // 如果行数超过5，则禁止添加新行
        if (numRows > 5) {
            layer.msg('已达到最大行数限制，不能再添加新行！');
            return;
        }
        var rowCount = $('#dataTable tbody tr').length + 1; // 获取当前行数并加1作为新行的序号

        var newRowHtml = '<tr>' +
            '<td>' + rowCount + '</td>' + // 新增自增序号列

            `<td>
            <div class="select-wrapper">
                <select name="earbugles" id="earNnumber" lay-filter="earbugles" lay-verify="required">
                    <option value="">请选择耳号</option>
                </select>
            </div>
        </td>` +
            `<td>
            <div class="select-wrapper">
                <select name="cottageName" id="buildings" lay-filter="cottageName" lay-verify="required">
                    <option value="">请选择栋舍</option>
                </select>
            </div>
        </td>` +
            `<td>
            <div class="select-wrapper">
                <select name="fieldName" id="columns" lay-filter="fieldName" lay-verify="required">
                    <option value="">请选择栏位</option>
                </select>
            </div>
        </td>` +
            `<td>
            <div class="select-wrapper">
                <select name="purSex" id="purSex" lay-verify="required">
                    <option value=0>母</option>
                <option value=1>公</option>
        </select>
    </div>
</td>` +
            '<td><input type="text" name="goodName"       id="goodName"        lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="package"        id="package"         lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="measuringUnit"  id="measuringUnit"   lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="quantityNumber" id="quantityNumber"  lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="averagePrice"   id="averagePrice"    lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="price"          id="price"           lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="priceDiscount"  id="priceDiscount"   lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="priceAdjust"    id="priceAdjust"     lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="pricePay"       id="pricePay"        lay-verify="" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td><input type="text" name="totalWeight"    id="totalWeight"     lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input"></td>' +
            '<td style="display:none"><input type="hidden" name="purId" value="2"></td>' +
            '<td><button class="layui-btn layui-btn-xs layui-btn-danger" onclick="saveRow(this)">保存</button><button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteRow(this)">删除</button></td>' +
            '</tr>';
        $('#dataTable tbody').append(newRowHtml);

        form.render(); // 重新渲染表单，使新增的输入框生效

        //绑定耳号
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesAllInfo',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#earNnumber');
                    $.each(enumData, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.earNnumber).text(item.earNnumber);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });
        // //绑定摘要
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/DigestType',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#zhaiyao');
                    $.each(enumData, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.value).text(item.text);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });
        //绑定栋舍
        var data = [];
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/CootList',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    data = res; // 直接使用返回的数据
                    var select = $('#buildings');
                    $.each(data, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        //人员列表
        $(document).ready(function () {
            $.ajax({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/PrincipalType', // 后端枚举数据接口地址
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    var enumData = res; // 直接使用返回的数据
                    var select = $('#rommss');
                    $.each(enumData, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.value).text(item.text);
                        select.append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        // 栋舍栏位二级联动
        $('#buildings').change(function () {
            var name = $("#buildings").val();
            var id = 0;
            $.each(data, function (index, item) {
                if (name == item.name) {
                    id = item.id;
                }
            });
            //监听到了下拉框选择的选项，传递过来
            $.get({
                url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/FieidList', // 后端枚举数据接口地址
                data: {
                    id: id
                },
                dataType: "json",
                success: function (res) {
                    $("#columns").empty();
                    var option = '<option value=" ">' + "请选择栏位" + '</option>';
                    $("#columns").append(option);
                    $.each(res, function (index, item) {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.name).text(item.name);
                        $('#columns ').append(option);
                    });
                    // 手动触发 layui 组件的渲染
                    layui.form.render('select');
                },
                error: function () {
                    // 处理 AJAX 请求失败的情况
                    console.error('Failed to fetch data for dropdown.');
                }
            });
        });

        form.render(); // 重新渲染表单，使新增的输入框生效
    });

    $('#saveDataBtn').on('click', function () {
        // 执行保存所有数据的操作，您可以根据需要补充逻辑
        console.log('保存数据');
    });
});

var $ = layui.$;
function saveRow(btn) {
    //赋值
    var formData = {
        earbugles: $('#earNnumber').val(),
        cottageName: $('#buildings').val(),
        fieldName: $('#columns').val(),
        purSex: $('#purSex').val(),
        goodName: $('#goodName').val(),
        package: $('#package').val(),
        measuringUnit: $('#measuringUnit').val(),
        quantityNumber: $('#quantityNumber').val(),
        averagePrice: $('#averagePrice').val(),
        price: $('#price').val(),
        priceDiscount: $('#priceDiscount').val(),
        priceAdjust: $('#priceAdjust').val(),
        pricePay: $('#pricePay').val(),
        totalWeight: $('#totalWeight').val(),
    };
    //验证
    if (formData.earbugles == "") {
        layer.msg('耳号不能为空！');
        return;
    }
    if (formData.cottageName == "") {
        layer.msg('栋舍不能为空！');
        return;
    }
    if (formData.goodName == "") {
        layer.msg('商品名称不能为空！');
        return;
    }
    if (formData.package == "") {
        layer.msg('标包不能为空！');
        return;
    }
    if (formData.measuringUnit == "") {
        layer.msg('计量单位不能为空！');
        return;
    }
    if (formData.quantityNumber == "") {
        layer.msg('只均单价不能为空！');
        return;
    }
    if (formData.price == "") {
        layer.msg('金额不能为空！');
        return;
    }
    if (formData.priceDiscount == "") {
        layer.msg('单位折扣不能为空！');
        return;
    }
    if (formData.priceAdjust == "") {
        layer.msg('调整金额不能为空！');
        return;
    }
    if (formData.pricePay == "") {
        layer.msg('结算金额不能为空！');
        return;
    }
    if (formData.totalWeight == "") {
        layer.msg('总重量不能为空！');
        return;
    }

    console.log(formData)

    $.ajax({
        type: 'post',
        url: 'http://10.31.60.18:8000/AuthorizationSetRout/api/EntityPurchase/EntityPurchaseCottage',
        data: JSON.stringify(formData), // 将表单数据转为JSON格式
        contentType: 'application/json',
        success: function (res) {
            if (res > 0) {
                var icon = 0;
                layer.alert('新增成功', {
                    icon: 1,
                    shadeClose: true,
                    title: "新增",
                }, function () {
                    location.href = "/EntityPurchase/ShowEntityPurchase";
                });
            } else {
                layer.msg('添加失败：');
            }
        },
        error: function (xhr, status, error) {
            console.error(error);
        }
    });
}
// 删除行的函数
function deleteRow(btn) {
    $(btn).closest('tr').remove();
}